<template>
  <el-form ref="ruleFormRef" style="max-width: 500px" :model="ruleForm" :rules="rules">
    <el-form-item label="学科" prop="name">
      <el-input v-model="ruleForm.name" />
    </el-form-item>
    <el-form-item label="年级" prop="level">
      <el-select v-model="ruleForm.level" placeholder="请选择年级" @change="levelChange">
        <el-option 
          :label="item.name" 
          :value="item.value" 
          v-for="item in levelStore.list" 
          :key="item.value" 
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        提交
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { useLevelStore } from '@/stores/level'
import { subjectAdd, subjectSelect, type subjectParamsAddType } from '@/api/jiaoyu'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const levelStore = useLevelStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<subjectParamsAddType>({
  name: '',
  level: '',
  id: null,
  levelName: ""
})

const rules = ref<FormRules<subjectParamsAddType>>({
  name: [
    { required: true, message: '请输入学科名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度应为 2 到 20 个字符', trigger: 'blur' },
  ],
  level: [
    { required: true, message: '请选择年级', trigger: 'change' },
  ]
})

// 根据路由ID获取学科详情
const fetchSubjectData = async () => {
  const id = route.params.id
  if (id && typeof id === 'string') {
    try {
      console.log(`正在获取学科数据，ID: ${id}`)
      const res = await subjectSelect(parseInt(id))
      
      if (res.code === 1 && res.response) {
        ruleForm.value = {
          id: res.response.id,
          name: res.response.name,
          level: res.response.level.toString(), // 确保转换为字符串
          levelName: res.response.levelName
        }
        console.log('获取到的学科参数:', res.response)
      } else {
        ElMessage.error(res.message || '获取学科信息失败')
        console.error('API返回错误:', res)
      }
    } catch (error) {
      console.error('获取学科信息时出错:', error)
      ElMessage.error('获取学科信息失败，请稍后重试')
    }
  } else if (id) {
    console.warn('非预期的ID类型:', id)
  }
}

// 年级选择变更处理
function levelChange(val: string | number) {
  const level = levelStore.list.find(item => item.value == val)
  if (level) {
    ruleForm.value.levelName = level.name
  } else {
    ruleForm.value.levelName = ""
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      console.log('提交表单数据:', ruleForm.value)
      subjectAdd(ruleForm.value).then(res => {
        if (res.code === 1) {
          ElMessage.success('提交成功')
          router.push('/xuekelist')
        } else {
          ElMessage.error(res.message || '提交失败')
          console.error('提交失败:', res)
        }
      }).catch(error => {
        console.error('提交请求出错:', error)
        ElMessage.error('提交请求出错')
      })
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  // 如果是编辑模式，重置后重新获取数据
  if (route.params.id) {
    ruleForm.value = {
      name: '',
      level: '',
      id: null,
      levelName: ""
    }
  } else {
    ruleForm.value = {
      name: '',
      level: '',
      id: null,
      levelName: ""
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSubjectData()
})
</script>